package com.ragdollcat.thirdaicodegenerate.service.impl;

import cn.hutool.core.util.ObjUtil;
import com.mybatisflex.core.query.QueryWrapper;
import com.ragdollcat.thirdaicodegenerate.constants.AppConstant;
import com.ragdollcat.thirdaicodegenerate.exception.ErrorCode;
import com.ragdollcat.thirdaicodegenerate.exception.ThrowUtils;
import com.ragdollcat.thirdaicodegenerate.model.entity.App;
import com.ragdollcat.thirdaicodegenerate.model.entity.FileNode;
import com.ragdollcat.thirdaicodegenerate.model.entity.ProjectVersionCtl;
import com.ragdollcat.thirdaicodegenerate.model.entity.User;
import com.ragdollcat.thirdaicodegenerate.model.vo.app.FileContentVO;
import com.ragdollcat.thirdaicodegenerate.model.vo.app.FileHistoryVO;
import com.ragdollcat.thirdaicodegenerate.model.vo.app.FileNodeVO;
import com.ragdollcat.thirdaicodegenerate.service.*;
import com.ragdollcat.thirdaicodegenerate.util.FileContentUtil;
import com.ragdollcat.thirdaicodegenerate.util.FileTreeUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class AppVersionCtlServiceImpl implements AppVersionCtlService {

    @Resource
    private UserService userService;

    @Resource
    private AppService appService;

    @Resource
    private ChatHistoryService chatHistoryService;

    @Resource
    private ProjectVersionCtlService projectVersionCtlService;


    @Override
    public FileNodeVO getLatestFileList(Long appId, HttpServletRequest httpServletRequest) {
        App app = appService.getById(appId);
        //1.参数校验
        this.checkParams(app, httpServletRequest);
        //2.拼接文件名称
        String codeGenType = app.getCodeGenType();
        Integer version = app.getVersion();
        String dirName = codeGenType + "_" + appId;
        String fullDirPath = AppConstant.SAVE_PATH + dirName;
        FileNodeVO fileNodeVO = new FileNodeVO();
        List<FileNode> fileNodes = FileTreeUtil.buildTreeFromFileSystem(fullDirPath);
        fileNodeVO.setFileNodeList(fileNodes);
        fileNodeVO.setVersion(version);
        return fileNodeVO;
    }

    @Override
    public FileContentVO getFileContentByNameAndId(Long appId, String fileName, HttpServletRequest httpServletRequest) {
        App app = appService.getById(appId);
        //参数校验
        this.checkParams(app, httpServletRequest);
        //2.拼接文件名称
        String codeGenType = app.getCodeGenType();
        String dirName = codeGenType + "_" + appId;
        String fullDirPath = AppConstant.SAVE_PATH + dirName;
        //3.找到fullDirPath的fileName的文件，然后封装成FileContentVO对象返回
        return FileContentUtil.getFileContent(fullDirPath, fileName);
    }


    @Override
    public List<FileHistoryVO> getFileHistoryByNameAndId(Long appId, String fileName, HttpServletRequest httpServletRequest) {
        App app = appService.getById(appId);
        User user = userService.getLoginUser(httpServletRequest);
        //参数校验
        this.checkParams(app, httpServletRequest);
        //2.拼接文件名称
        String codeGenType = app.getCodeGenType();
        //3.都需要从历史记录表中取得
        ArrayList<FileHistoryVO> fileHistoryVOS = new ArrayList<>();

        //根据appId 文件名 userId查vue版本控制表
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("appId", appId);
        queryWrapper.eq("fileName", fileName);
        queryWrapper.eq("userId", user.getId());
        List<ProjectVersionCtl> projectVersionCtls = projectVersionCtlService.list(queryWrapper);

        projectVersionCtls.forEach(vueProjectVersionCtl -> {
            FileHistoryVO fileHistoryVO = new FileHistoryVO();
            BeanUtils.copyProperties(vueProjectVersionCtl, fileHistoryVO);
            fileHistoryVO.setCreatedBy(user.getUserName());
            fileHistoryVO.setDescription(vueProjectVersionCtl.getMessage());
            fileHistoryVOS.add(fileHistoryVO);
        });

        return fileHistoryVOS;

    }


    @Override
    public FileContentVO getFileContentByVersion(Long appId, String fileName, Integer version, HttpServletRequest httpServletRequest) {
        App app = appService.getById(appId);
        //参数校验
        this.checkParams(app, httpServletRequest);
        //2.拼接文件名称
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("appId", appId);
        queryWrapper.eq("fileName", fileName);
        queryWrapper.eq("version", version);
        ProjectVersionCtl projectVersionCtl = projectVersionCtlService.getOne(queryWrapper);

        return FileContentVO.builder()
                .content(projectVersionCtl.getContent()).build();
    }

    /**
     * 参数校验
     **/
    private void checkParams(App app, HttpServletRequest httpServletRequest) {
        User user = userService.getLoginUser(httpServletRequest);
        ThrowUtils.throwIf(ObjUtil.isEmpty(app), ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(ObjUtil.isEmpty(user), ErrorCode.NOT_LOGIN_ERROR);
        ThrowUtils.throwIf(!app.getUserId().equals(user.getId()), ErrorCode.NO_AUTH_ERROR);
    }

//
//    public static void main(String[] args) {
//        System.out.println(FileTreeUtil.buildTreeFromFileSystem("D:\\Idea_workspace\\2025\\third-ai-code-generate\\tmp\\code\\vue_project_340685275397222400_1"));
//    }
}
